package com.shirojwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.sql.Struct;
import java.util.Date;

/**
 * @author chenguo
 * @date 2021/10/12 10:09 上午
 */
@Slf4j
public class JwtUtil {
    private static final Long EXPIRE_TIME = 5 * 60 * 1000L;
    private static final String SECRET = "SHIRO+JWT";

    public static String createToken(String username){
        String token = null;
        try{
            Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            token = JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(expireDate)
                    .sign(algorithm);
        }catch (UnsupportedEncodingException e){
            log.error("Failed to create token. {}", e.getMessage());
        }
        return token;
    }

    public static boolean verify(String token, String username){
        boolean isSuccess = false;
        try{
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            verifier.verify(token);
            isSuccess = true;
        }catch (UnsupportedEncodingException e){
            log.error("Token is invalid. {}", e.getMessage());
        }
        return isSuccess;
    }

    public static String getUsernameFromToken(String token){
        try{
            DecodedJWT decoded = JWT.decode(token);
            return decoded.getClaim("username").asString();
        }catch (JWTDecodeException e){
            log.error("Failed to Decode jwt. {}", e.getMessage());
            return null;
        }
    }
}
